import { backupLayoutRuoters } from './router'
import type { LayoutRouterRaw, RouterTabRaw } from '@/@type'
import { useUsersStore, useAppStore } from '@/stores'
import { excludeTabRouters } from '@/config'
import { storeToRefs } from 'pinia'
import type { Router } from 'vue-router'

export default function (router: Router) {
  /**
 * 移除没有权限或者不属于菜单上的路由，构建左侧菜单路有树
 * @param routers
 * @param parentPath
 * @param childIdx
 * @param parent
 * @returns
 */
  async function recursionRouters (
    routers: Array<LayoutRouterRaw>,
    parentPath?: string,
    childIdx?: number,
    parent?: Array<LayoutRouterRaw>
  ) {
    const { getPermissionCodes } = useUsersStore()
    const permissions: unknown[] = await getPermissionCodes()
    for (let i = 0; i < routers.length; i++) {
      if (parentPath) {
        routers[i].path = routers[i].path ? parentPath + '/' + routers[i].path : parentPath
      }
      delete routers[i].component
      if (routers[i].meta?.noMenu ||
      (
        routers[i].meta?.permissionCode &&
        !permissions.includes(routers[i].meta?.permissionCode)
      )
      ) {
        routers.splice(i, 1)
        if (!routers.length) {
          if (parent) {
            parent.splice(childIdx || 0, 1)
          }
          return
        }
        i--
        continue
      }
      const children = routers[i]?.children as Array<LayoutRouterRaw>
      if (children?.length) {
        recursionRouters(children, routers[i].path, i, routers)
      }
    }
  }

  recursionRouters(backupLayoutRuoters)
  const { menu } = storeToRefs(useAppStore())
  menu.value = backupLayoutRuoters

  /**
 * 获取路由权限列表内第一个路由地址path
 * @param route
 * @returns
 */
  function findHasPermissionFirstRoute (route: LayoutRouterRaw): string {
    if (!route?.children?.length) {
      return route?.path
    }
    return findHasPermissionFirstRoute(route.children[0] as LayoutRouterRaw)
  }
  const { routerTabList, currentFullPath, includeCaches, multipleTab } = storeToRefs(useAppStore())
  router.beforeEach(async (to, _from, next) => {
    const { getPermissionCodes } = useUsersStore()
    const permissions: unknown[] = await getPermissionCodes()
    if (to.meta.permissionCode) {
      if (permissions.includes(to.meta.permissionCode)) {
        next()
      } else {
        if (to.fullPath === '/') {
          if (!permissions.length) {
            next({ path: '/login' })
            return false
          }
          // 访问首页无权限时自动跳转到第一个有权限的路由
          const path = findHasPermissionFirstRoute(backupLayoutRuoters[0])
          next({ path })
        } else {
          next({ name: 'Error403' })
          return false
        }
      }
    } else {
      next()
    }
    if (!multipleTab.value) return
    // 路由遍历生成多标签以及为多标签添加缓存
    // 若有不需要加入到多标签页的路由可在 excludeTabRouters 内配置
    if (!excludeTabRouters.includes(to.name as string)) {
      const exist = routerTabList.value.find(o => o.fullPath === to.fullPath)
      const { meta, name, fullPath, path, query } = to
      if (!exist) {
        routerTabList.value.push({
          meta,
          name,
          fullPath,
          path,
          query
        } as RouterTabRaw)
      }
      if (!includeCaches.value.find(name => name === fullPath)) {
        includeCaches.value.push(fullPath)
      }
      currentFullPath.value = to.fullPath
    }
  })

  /**
   * 监听浏览器刷新动作，存储多标签页到sessionStorage
   */
  window.addEventListener('beforeunload', function () {
    if (multipleTab.value) {
      this.window.sessionStorage.setItem('router-tab', JSON.stringify(routerTabList.value))
    }
  })
}
